package com.hongshan.wallet.util

import com.hongshan.wallet.http.HttpClient
import com.hongshan.wallet.tryRun
import com.hongshan.wallet.urlEncode
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream


/**
 * Copyright Zhangxx.
 * Copyright (c) 2019
 * All rights reserved
 *
 * @project  : Wallet
 * @package  : com.example.wallet.util
 * @author   : zhangxx
 * @date     : 2019/4/11
 * @email    : qq957413212@hotmail.com
 * @desc     : //TODO
 */
object NetworkFileUtils {
    fun download(body: ResponseBody, file: File): Boolean {
        var inputStream: InputStream? = null
        var outputStream: OutputStream? = null
        try {
            val fileReader = ByteArray(4096)
            var fileSizeDownloaded: Long = 0
            inputStream = body.byteStream()
            outputStream = FileOutputStream(file)
            while (true) {
                val read = inputStream!!.read(fileReader)
                if (read == -1) {
                    break
                }
                outputStream.write(fileReader, 0, read)
                fileSizeDownloaded += read.toLong()
            }
            outputStream.flush()
            return true
        } catch (e: IOException) {
            inputStream?.close()
            outputStream?.close()
            return false
        }
    }

    fun upload(url: String, filePath: String, callback: (result: String?) -> Unit) {
        val file = File(filePath)
        val requestBody = RequestBody.create(MediaType.parse("*/*"), file)
        val multipartBody = MultipartBody.Builder()
            .setType(MultipartBody.FORM)
            .addFormDataPart("file", urlEncode(file.name), requestBody)
            .build()
        GlobalScope.launch(Dispatchers.Main) {
            val result = GlobalScope.async(Dispatchers.IO) {
                tryRun { HttpClient.httpApi.uploadFile(url, multipartBody).execute() }
            }
            val body = result.await()?.body()
            if (body?.code == 0) {
                callback.invoke(body.data["url"])
            } else{
                callback.invoke(null)
            }
        }
    }
}